package hamaster.jpbc.pbc;

import it.unisa.dia.gas.jpbc.Element;

import java.util.Properties;

public class PlainText implements Propertiable {

	public final static String DATA_POSTFIX = "text";
	public final static String LENGTH_POSTFIX = "length";

	private Element element;

	private int length;

	public PlainText() {
	}

	public Element getElement() {
		return element;
	}

	public void setElement(Element element) {
		this.element = element;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	@Override
	public boolean setFromProperties(Properties properties, String prefix) {
		String ek = DATA_POSTFIX;
		String lk = LENGTH_POSTFIX;
		if (prefix != null && prefix.trim().length() > 0) {
			ek = prefix + "." + DATA_POSTFIX;
			lk = prefix + "." + LENGTH_POSTFIX;
		}
		String es = properties.getProperty(ek);
		String ls = properties.getProperty(lk);
		if (es == null || ls == null)
			return false;
		element = PBC.instance().getPairing().getGT().newElement();
		element.setFromBytes(PBCDriver.unhex(es));
		length = Integer.parseInt(ls);
		return true;
	}

	@Override
	public Properties toProperties(String prefix) {
		String ek = DATA_POSTFIX;
		String lk = LENGTH_POSTFIX;
		if (prefix != null && prefix.trim().length() > 0) {
			ek = prefix + "." + DATA_POSTFIX;
			lk = prefix + "." + LENGTH_POSTFIX;
		}
		Properties p = new Properties();
		p.setProperty(ek, PBCDriver.hex(element.toBytes()));
		p.setProperty(lk, length + "");
		return p;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		PlainText other = (PlainText) obj;
		if (element == null) {
			if (other.element != null)
				return false;
		} else if (!element.equals(other.element))
			return false;
		return true;
	}

	@Override
	protected void finalize() throws Throwable {
		element.setToRandom();
		super.finalize();
	}

	@Override
	public String toString() {
		return "[PlainText]\nelement=" + element + "\nlength=" + length + "\n";
	}

}
